import 'dart:async';

import 'package:flutter/material.dart';
import 'package:top_foundation/component/dialog/index.dart';

import '../../helper/utils/util.dart';
import 'index.dart';

class AppLogController {
  static final AppLogController _instance = AppLogController._interval();
  factory AppLogController() {
    return _instance;
  }
  AppLogController._interval() {
    onInit();
  }

  final state = AppLogState();

  void register<R>(R Function() body) {
    FlutterError.onError = _reportErrorAndLog;
    runZonedGuarded(
      body,
      (error, stack) {
        _makeDetails(error, stack);
      },
      zoneSpecification: ZoneSpecification(
        print: (self, parent, zone, line) {
          _collectLog(line);
        },
      ),
    );
  }

  void _collectLog(String line) {
    //收集日志
    state.logs.add(line);
  }

  void _reportErrorAndLog(FlutterErrorDetails details) async {
    //上报错误和日志逻辑
    state.errors.add(details.toString());
    if (await SpUtil().setJSON('app_log', {'data': state.errors})) {
      Get.log('日志保存成功');
    }

    var action = await showAlert(
        title: '有错误日志', msg: details.toString(), sureText: '点击前往');
    if (action == 1) {
      _toLog();
    }
  }

  void _makeDetails(Object obj, StackTrace stack) async {
    // 构建错误信息
    var e = obj.toString();
    state.errors.add(e);
    var action = await showAlert(title: '有错误日志', msg: e, sureText: '点击前往');
    if (action == 1) {
      _toLog();
    }
  }

  void _toLog() {
    Get.to(() => const AppLogPage());
  }

  void onInit() {
    state.titles = ['日志', '异常'];
    state.tabCtrl = TPTabBarController()..updateTitles(state.titles);
    var data = SpUtil().getJSON('app_log');
    if (data is Map) {
      var err = data['data'] as List<String>?;
      state.errors = err ?? [];
    }
  }
}
